package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
@Slf4j
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;
    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract statusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if(statusContract == null
                || statusContract.getStatusInfo()==null
                || statusContract.getStatusInfo().size()<=0) return;

        // 如果是非正常工单，则创建维修工单
        if(statusContract.getStatusInfo().stream().anyMatch(s-> !s.isStatus())){
            try {
                // 根据售货机编号，查询售货机
                var vmInfo = vmService.getVMInfo(statusContract.getInnerCode());
                var userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
                var task = new TaskViewModel();
                task.setUserId(userId);
                task.setDesc("维修工单");
                task.setInnerCode(vmInfo.getInnerCode());
                task.setProductType(VMSystem.TASK_TYPE_REPAIR);
                task.setCreateType(0);
                taskService.create(task);
            } catch (Exception e) {
                System.err.println(e.getMessage());
                log.error("创建自动维修工单失败，msg is:"+jsonMsg);
            }
        }

    }
}
